<script setup name="DocRedSheetTemplate">
import router from "@/router/index.js";
import SelectTemplateList from "@/views/common/selectTemplateList.vue";
import {
  addTemplate,
  cloneTemplate,
  deleteTemplate, disableTemplate, enableTemplate,
  getRedSheetTemplatePageList
} from "@/api/document/redSheetTemplate.js";
import {selectTemplateFunctions} from "@/utils/selectTemplate.js";
import {onActivatedFunctions} from "@/utils/common.js";
import useAppStore from "@/store/modules/app.js";

const device = computed(() => useAppStore().device);
const {proxy} = getCurrentInstance()
const uniqueId = ref("")
const {templateStatus} = proxy.useDict(["templateStatus", true])
const templateList = ref([])
const addOpen = ref(false)
const addTitle = ref('')
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
//克隆模板
const cloneOpen = ref(false)

// 列显隐信息
const columns = ref({
  name: {key: 'name', label: `模板名称`, visible: true},
  status: {key: 'status', label: `状态`, visible: true},
  userName: {key: 'userName', label: `创建人`, visible: true},
  updateTime: {key: 'updateTime', label: `修改时间`, visible: true},
  createTime: {key: 'createTime', label: `创建时间`, visible: false}
})
const data = reactive({
  addForm: {
    name: '',
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    userName: undefined,
    status: undefined
  },
  rules: {
    name: [{required: true, message: "模板名不能为空", trigger: "blur"}],
    memo: [{max: 255, message: "备注内容长度不能超过 255 个字符", trigger: "blur"}]
  }
})
const {queryParams, addForm, rules} = toRefs(data)
const statusStyles = {
  '新建': 'info',
  '启用': 'success',
  '停用': 'danger'
}
const getTagType = function (status) {
  return statusStyles[status] || 'info';
}
const {
  openTemplateDialog,
  closeTemplateDialog,
  getTemplateList
} = selectTemplateFunctions(getRedSheetTemplatePageList, '选择克隆模板', cloneOpen)

onMounted(() => {
  getList()
})

onActivatedFunctions(getList, uniqueId)

function getList() {
  loading.value = true
  getRedSheetTemplatePageList(queryParams.value).then(res => {
    loading.value = false
    templateList.value = res.list
    total.value = res.total
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirmAndExecuteJS('是否确认删除名为"' + row.data.name + '"的模板记录?', deleteTemplate, row.data.id, getList)
}

/** 重置操作表单 */
function reset() {
  addForm.value = {
    id: undefined,
    name: undefined,
    memo: undefined,
  }
  proxy.resetForm("templateRef")
}

/** 取消按钮 */
function cancel() {
  addOpen.value = false
  reset()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  addOpen.value = true
  addTitle.value = "新建模板"
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["templateRef"].validate(valid => {
    if (valid) {
      addTemplate(addForm.value).then(newTemplateId => {
        addOpen.value = false
        proxy.$modal.msgSuccess("新增成功")
        getList()
        router.push({
          path: '/document/redSheetTemplate/view/' + newTemplateId,
          query: {isCanEdit: true, customTitle: '公文模板 - ' + addForm.value.name}
        })
      })
    }
  })
}

function handleSelectedTemplate(template) {
  cloneTemplate(template.data.id).then(newTemplateId => {
    cloneOpen.value = false
    addOpen.value = false
    proxy.$modal.msgSuccess("克隆成功")
    router.push({
      path: '/document/redSheetTemplate/view/' + newTemplateId,
      query: {isCanEdit: true, customTitle: '公文模板 - ' + template.data.name + '【NEW】'}
    })
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const templateId = row.data.id
  router.push({
    path: '/document/redSheetTemplate/view/' + templateId,
    query: {isCanEdit: row.button.update, customTitle: '公文模板 - ' + row.data.name}
  })
}

function handleEnable(row) {
  proxy.$modal.confirmAndExecuteJS('是否确认启用名称为"' + row.data.name + '"的模板记录?', enableTemplate, row.data.id, getList)
}

function handleDisable(row) {
  proxy.$modal.confirmAndExecuteJS('是否确认停用名称为"' + row.data.name + '"的模板记录?', disableTemplate, row.data.id, getList)
}

</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--模板数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="模板名称" prop="name">
            <el-input
                v-model="queryParams.name"
                placeholder="请输入模板名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建人" prop="userName">
            <el-input
                v-model="queryParams.userName"
                placeholder="请输入创建人姓名"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
                v-model="queryParams.status"
                placeholder="模板状态"
                clearable
                style="width: 240px"
                :empty-values="[null, undefined]"
            >
              <el-option
                  v-for="dict in templateStatus"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['doc:redSheetTemplate:add']"
            >新增
            </el-button>
          </el-col>

          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="templateList">
          <el-table-column :label="columns.name.label" key="data.name" prop="data.name" v-if="columns.name.visible" :show-overflow-tooltip="true" min-width="150">
            <template #default="scope">
              <el-link @click="handleUpdate(scope.row)" type="primary">
                {{scope.row.data.name}}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column :label="columns.status.label" key="data.status" prop="data.status" v-if="columns.status.visible" width="100">
            <template #default="scope">
              <el-text :type="getTagType(scope.row.data.status)"> {{ scope.row.data.status }} </el-text>
            </template>
          </el-table-column>
          <el-table-column :label="columns.userName.label" key="data.userName" prop="data.userName" v-if="columns.userName.visible" width="180" :show-overflow-tooltip="true" />
          <el-table-column :label="columns.updateTime.label" key="data.updateTime" prop="data.updateTime" v-if="columns.updateTime.visible" width="190" />
          <el-table-column :label="columns.createTime.label" key="data.createTime" prop="data.createTime" v-if="columns.createTime.visible" width="190" />
          <el-table-column label="操作" :fixed="device === 'desktop' ? 'right' : null" class-name="small-padding" :width="device === 'mobile' ? '130' : '200'">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-if="scope.row.button.update">修改
              </el-button>
              <el-button link type="success" icon="Select" @click="handleEnable(scope.row)"
                         v-if="scope.row.button.enable">启用
              </el-button>
              <el-button link type="danger" icon="CloseBold" @click="handleDisable(scope.row)"
                         v-if="scope.row.button.disable">停用
              </el-button>
              <el-button link type="info" icon="Delete" @click="handleDelete(scope.row)"
                         v-if="scope.row.button.delete">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加模板对话框-->
    <el-dialog :title="addTitle" v-model="addOpen" width="800px" append-to-body :close-on-click-modal="false">
      <el-form @submit.native.prevent :model="addForm" :rules="rules" ref="templateRef" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入模板名称" maxlength="100">
                <template #append>
                  <el-button type="success" @click="openTemplateDialog()">从已有的文件模板克隆</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注信息">
              <el-input v-model="addForm.memo" type="textarea" placeholder="请输入备注下信息"
                        maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 克隆模板对话框 -->
      <SelectTemplateList
          :is-open="cloneOpen"
          @getTemplateList="getTemplateList"
          @handleSelectedTemplate="handleSelectedTemplate"
          @close="closeTemplateDialog"
          templateType="docCloneRedSheetTemplate"/>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

